import { useState, useEffect } from "react";
import {
  useRoutes,
  Outlet,
  Link,
  useLocation,
  useNavigate,
} from "react-router-dom";
import routes from "./router";
import { message } from "antd";

// 去往首页的组件
function ToPage1() {
  const navigateTo = useNavigate();
  useEffect(() => {
    navigateTo("/page1");
    message.warning("您已经登陆过。");
  }, []);
  return <div></div>;
}
// 去往登录页的组件
function ToLogin() {
  const navigateTo = useNavigate();
  // 加载完组件之后执行
  useEffect(() => {
    navigateTo("/login");
    message.warning("您还没有登录，请登陆后访问。");
  }, []);
  return <div></div>;
}
// 路由守卫
function BeforeRouterEnter() {
  const outlet = useRoutes(routes);
  const location = useLocation();
  /*
    后台管理系统两种经典的跳转情况
    1.如果访问的是登录页面，并且有token，跳转到首页
    2.如果访问的不是登陆页面，并且没有token，跳转到登录页
    3.其余的正常放行
  */
  let token = localStorage.getItem("react-token");
  if (location.pathname === "/login" && token) {
    //登录页
    return <ToPage1 />;
  }
  if (location.pathname !== "/login" && !token) {
    return <ToLogin />;
  }

  return <>{outlet}</>;
}

function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      {/* 顶级组件*/}
      {/* <Link to="/home">Home</Link>
            <Link to="/about">About</Link>
            <Link to="/user">User</Link> */}
      {/* 占位符,类似于窗口,用于展示组件,像vue中的router-view */}
      {/* <Outlet></Outlet> */}
      <BeforeRouterEnter />
    </div>
  );
}

export default App;
